package com.hoyue.servlet;

import com.hoyue.bean.BackPicture;
import com.hoyue.service.BackPicService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Hoyue_network1
 * @version 1.0
 * Creat by 2018/8/22 16:22
 */
@WebServlet("/BackPicServlet")
public class BackPicServlet extends HttpServlet{
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("method");//获取方法名
		if(name == null || name.isEmpty()){
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method = getClass().getDeclaredMethod(name, HttpServletRequest.class,HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到"+name+"方法，请检查该方法是否存在");
		}

		try {
			method.invoke(this, request,response);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法"+name+",内部发生了异常");
			throw new RuntimeException(e);
		}

	}

	BackPicService backPicService = new BackPicService();

	// 后台获取轮播图
	protected void getBackPic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);

		List<BackPicture> backPicture = backPicService.getBackPicture();

		request.setAttribute("pic",backPicture);
		request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/admin/adv.jsp").forward(request,response);
	}

	// 后台编辑轮播图
	protected void editBackPic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		BackPicture backPicture = new BackPicture();
		// 收集数据的容器
		Map<String,Object> map = new HashMap<>();
		// 创建工厂类
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获取文件上传对象
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 轮播图id，用于获取address
		int id = 0;

		// 解析request集合
		try {
			// 每一个FileItem对应一个Form表单的输入项
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item:items) {
				if(item.isFormField()) {	// 是普通的表单项
					String fileName = item.getFieldName();
					if(fileName.equals("id")) { id = Integer.parseInt(item.getString("UTF-8")); }
					String fileValue = item.getString("UTF-8");
					map.put(fileName, fileValue);	//设置到map,用于后面进行封装
				} else {	// 是文件上传的表单项
					String address = backPicService.getAddressById(id);
					String name = address.substring(address.lastIndexOf("/") + 1);

					String photoFolder = request.getServletContext().getRealPath("page/images");
					// 通过item.getInputStream()获取浏览器上传的文件的输入流
					InputStream inputStream = item.getInputStream();

					// 创建输入流写入文件
					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);
					// copy
					IOUtils.copy(inputStream,outputStream);

					// 关闭资源
					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("address",address);
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		// 封装数据
		try {
			BeanUtils.populate(backPicture, map);
		} catch (Exception  e) {
			e.printStackTrace();
		}

		// 调用service
		BackPicService backPicService = new BackPicService();
		backPicService.updatePicture(backPicture);

		request.getRequestDispatcher(request.getContextPath() + "/BackPicServlet?method=getBackPic").forward(request, response);
	}
}
